#version 330 // 选择GLSL版本

// 接受顶点着色器出入的数据
in vec3 ex_PosW;
in vec3 ex_NormalW;
in vec2 ex_TexCoord;

uniform vec3 eyePosW;		// 世界空间眼睛位置
uniform vec3 lightPosW;		// 世界空间光源位置
uniform vec4 lightColor;	// 光照颜色

// 定义材质结构
struct Material
{
	vec4 ambient;
	vec4 diffuse;
	vec4 specular;
};

uniform Material material;		// 材质
uniform vec4 g_Ambient;			// 全局环境光
uniform sampler2D texSampler;	// 2D纹理采样器

out vec4 finalColor;

void main(void)
{
	// 计算材质辐射度
	vec4 emissive = material.ambient;

	// 计算漫射光
	vec3 lightVec = lightPosW - ex_PosW;
	float d = 100.0f;

	vec3 N = normalize(ex_NormalW);
	vec3 L = normalize(lightVec);
	float NdotL = max( dot(N, L), 0.0f );
	vec4 diffuse = NdotL *  lightColor * material.diffuse;

	// 计算镜面高光
	vec3 V = normalize( eyePosW - ex_PosW );
	vec3 H = normalize( L + V );
	vec3 R = reflect( -L, N );
	float RdotV = max( dot(R, V), 0.0f ); // Phong lighting model
	float NdotH = max( dot(N, H), 0.0f ); // Blinn-Phong lighting model
	vec4 specular = pow( RdotV, material.specular.w ) * lightColor * material.specular;

	float atten = 1.0f;// / (0.1f*d);
	diffuse *= atten;
	specular *= atten;

	// 对最终光照后的颜色进行求和并与纹理素进行调制
	finalColor = (emissive + g_Ambient + diffuse + specular) * texture(texSampler, ex_TexCoord);
}
